package com.yonyou.pmclouds.statistic.service.rmiimpl;

import com.alibaba.dubbo.config.annotation.Service;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.businessobject.util.SortListUtil;
import com.yonyou.pmclouds.organization.mapper.OrganizationMapper;
import com.yonyou.pmclouds.problemlog.entity.ProblemLogBillStatus;
import com.yonyou.pmclouds.problemlog.entity.ProblemLogVO;
import com.yonyou.pmclouds.procedure.rmiitf.ProcedureQuery;
import com.yonyou.pmclouds.project.entity.ProjectVO;
import com.yonyou.pmclouds.project.mapper.ProjectMapper;
import com.yonyou.pmclouds.project.rmiitf.ProjectSimpleQuery;
import com.yonyou.pmclouds.reason.entity.ProblemReasonRefVO;
import com.yonyou.pmclouds.reason.entity.ProblemReasonVO;
import com.yonyou.pmclouds.reason.rmiitf.ProblemReasonQuery;
import com.yonyou.pmclouds.statistic.entity.ProReasonCountVO;
import com.yonyou.pmclouds.statistic.entity.ProblemReasonPercentageVO;
import com.yonyou.pmclouds.statistic.entity.ProblemReasonViewVO;
import com.yonyou.pmclouds.statistic.entity.ProblemReportVO;
import com.yonyou.pmclouds.statistic.mapper.ProblemReasonAnalyseMapper;
import com.yonyou.pmclouds.statistic.rmiitf.ProblemReasonAnalyseRemoteService;
import com.yonyou.pmclouds.team.entity.TeamEnterpriseVO;
import com.yonyou.pmclouds.team.entity.TeamMemberVO;
import com.yonyou.pmclouds.team.mapper.TeamEnterpriseMapper;
import com.yonyou.pmclouds.team.mapper.TeamMapper;
import com.yonyou.pmclouds.team.rmiitf.ProjectRefWithTeamQuery;
import com.yonyou.pmclouds.team.rmiitf.TeamMemberQuery;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service(version = ApplicationConsts.APPLICATION_VERSION, interfaceClass = ProblemReasonAnalyseRemoteService.class)
public class ProblemReasonAnalyseRemoteServiceImpl implements ProblemReasonAnalyseRemoteService {


    @Autowired
    private ProblemReasonAnalyseMapper mapper;
    @Autowired
    private OrganizationMapper orgMapper;
    @Autowired
    private ProblemReasonQuery reasonQuery;
    @Autowired
    private ProjectRefWithTeamQuery projectRefQuery;
    @Autowired
    private ProjectSimpleQuery projectSimpleQuery;
    @Autowired
    private TeamMemberQuery teamMemberQuery;
    @Autowired
    private TeamMapper teamMapper;
    @Autowired
    private ProcedureQuery procedureQuery;
    @Autowired
    private TeamEnterpriseMapper enterpriseMapper;
    @Autowired
    private ProjectMapper projectMapper;

    private static final String FILTER_CODE_THREE_MONTH = "threeMonth";

    private static final String FILTER_CODE_HALF_YEAR = "halfYear";

    private static final String FILTER_CODE_A_YEAR = "aYear";

    @Override
    public List<ProReasonCountVO> queryProblemReasonAnalyse(String pk_tenant, String[] pkProjects, String start_date,
                                                            String end_date) throws BusinessException {

        List<ProblemLogVO> proLogList = mapper.queryProblemReasonAnalyse(pk_tenant, pkProjects, start_date, end_date);
        if (proLogList == null || proLogList.size() == 0)
            return null;

        Map<String, List<ProblemLogVO>> reasonMap = new HashMap<String, List<ProblemLogVO>>();
        String pk_problemreason = null;
        for (ProblemLogVO logVO : proLogList) {
            pk_problemreason = logVO.getPk_problemreason();
            if (reasonMap.get(logVO.getPk_problemreason()) == null) {
                reasonMap.put(pk_problemreason, new ArrayList<ProblemLogVO>());
            }
            reasonMap.get(pk_problemreason).add(logVO);
        }
        List<ProReasonCountVO> resultList = new ArrayList<ProReasonCountVO>();

        Map<String, ProblemReasonRefVO> reasonRefMap = reasonQuery.queryRefs(reasonMap.keySet().toArray(new String[0]));

        if (reasonRefMap == null || reasonRefMap.size() == 0)
            return resultList;

        for (String pk_reason : reasonMap.keySet()) {
            ProReasonCountVO newCountVO = new ProReasonCountVO();
            newCountVO.setPk_problemreason(pk_reason);
            newCountVO.setCount(reasonMap.get(pk_reason).size());
            newCountVO.setProblemreason_name(reasonRefMap.get(pk_reason) == null ? "" : reasonRefMap.get(pk_reason).getSname());

            resultList.add(newCountVO);
        }

        Collections.sort(resultList);

        return resultList;
    }

    public List<ProblemReasonPercentageVO> queryProblemReasonCount(String tenantId, String filterCode,String orgId) throws BusinessException {
        String startTime = getStartTime(filterCode);

        List<ProblemLogVO> logVOS = null;
        if(StringUtils.isNotEmpty(orgId)){
            Map<String, List<ProjectVO>>  proMap  = projectSimpleQuery.queryProjectsByOrgs(tenantId, new String[]{orgId});
            if(proMap != null){
                List<String> pkProList = new ArrayList<>();
                if(proMap.get(orgId) != null && proMap.get(orgId).size()>0){
                    for (ProjectVO projectVO : proMap.get(orgId)){
                        pkProList.add(projectVO.getPkProject());
                    }
                    // 查询该时间段内所有的问题记录
                    logVOS = mapper.queryProblemReasonPercentage(tenantId, startTime, pkProList.toArray(new String[0]));
                }
            }
        }else{
            logVOS = mapper.queryProblemReasonPercentage(tenantId, startTime, null);
        }

        if (logVOS == null || logVOS.size() <= 0) {
            return null;
        }
        Map<String, List<ProblemLogVO>> reasonMap = this.getReasonMap(logVOS);
        List<ProblemReasonPercentageVO> percentageVOList = new ArrayList<ProblemReasonPercentageVO>();
        // 通过问题原因类型ID查出问题原因类型描述
        Map<String, ProblemReasonRefVO> reasonRefMap = reasonQuery.queryRefs(reasonMap.keySet().toArray(new String[0]));

        if (reasonRefMap == null || reasonRefMap.size() == 0)
            return percentageVOList;
        int reasonTotal = 0;
        int loopCount = 0;
        int elseCount = 0;
        for (Map.Entry<String, List<ProblemLogVO>> entry : reasonMap.entrySet()) {
            String pk_reason = entry.getKey();
            int count = entry.getValue().size();
            reasonTotal += count;
            ProblemReasonPercentageVO percentageVO = new ProblemReasonPercentageVO();
            String problemName = reasonRefMap.get(pk_reason) == null ? "" : reasonRefMap.get(pk_reason).getSname();
            percentageVO.setCount(count);
            percentageVO.setProblemName(problemName);
            percentageVOList.add(percentageVO);
        }
        // 根据数量倒序排列
        SortListUtil.sort(percentageVOList, "count", "desc");
        // 问题原因显示占比最高的5个+其他
        List<ProblemReasonPercentageVO> resultList = new ArrayList<>();
        int totalPercentage = 0;
        for (ProblemReasonPercentageVO percentageVO : percentageVOList) {
            if (loopCount > 4) {
                elseCount += percentageVO.getCount();
            } else {
                int percentage = (int) Math.floor(percentageVO.getCount() * 100 / reasonTotal);
                totalPercentage += percentage;
                percentageVO.setPercentage(percentage);
                percentageVO.setTotalCount(reasonTotal);
                resultList.add(percentageVO);
            }
            loopCount++;
        }
        ProblemReasonPercentageVO reasonPercentageVO = new ProblemReasonPercentageVO();
        reasonPercentageVO.setProblemName("其他");
        reasonPercentageVO.setCount(elseCount);
        reasonPercentageVO.setTotalCount(reasonTotal);
        reasonPercentageVO.setPercentage(100 - totalPercentage);
        resultList.add(reasonPercentageVO);
        return resultList;
    }

    private Map<String, List<ProblemLogVO>> getReasonMap(List<ProblemLogVO> logVOS) {
        Map<String, List<ProblemLogVO>> reasonMap = new HashMap<>();
        for (ProblemLogVO logVO : logVOS) {
            if (reasonMap.get(logVO.getPk_problemreason()) == null) {
                reasonMap.put(logVO.getPk_problemreason(), new ArrayList<ProblemLogVO>());
            }
            reasonMap.get(logVO.getPk_problemreason()).add(logVO);
        }
        return reasonMap;
    }

    @Override
    public List<ProblemLogVO> queryOverdueCount(String tenantId, byte billStatus, String orgId) throws BusinessException {
        List<ProblemLogVO> problemLogVOList = mapper.queryOverdueCount(tenantId, billStatus);
        if(StringUtils.isEmpty(orgId)){
            return problemLogVOList;
        }

        List<ProblemLogVO> retProblemLogList = new ArrayList<>();
        // 根据组织ID进行过滤
        if(problemLogVOList != null && problemLogVOList.size() > 0){
            List<String> pkProjectList = new ArrayList<>();
            for(ProblemLogVO problemLogVO : problemLogVOList){
                pkProjectList.add(problemLogVO.getPk_project());
            }
            ProjectVO[] projectVOS = projectSimpleQuery.queryVOByIds(pkProjectList.toArray(new String[0]));
            Map<String, String> projectWithOrgMap = new HashMap<>();
            if(projectVOS != null && projectVOS.length > 0){
                for(ProjectVO projectVO : projectVOS){
                    projectWithOrgMap.put(projectVO.getPkProject(), projectVO.getPkOrg());
                }

                for(ProblemLogVO problemLogVO : problemLogVOList){
                    if(orgId.equalsIgnoreCase(projectWithOrgMap.get(problemLogVO.getPk_project()))){
                        retProblemLogList.add(problemLogVO);
                    }
                }
            }

        }

        return retProblemLogList;
    }

    @Override
    public TeamMemberVO[] queryTeamMemberById(String[] userIds) throws BusinessException {
        return teamMapper.queryByPkUsers(userIds);
    }

    @Override
    public TeamEnterpriseVO[] queryTeamEnterpriseById(String[] enpIds) throws BusinessException {
        return enterpriseMapper.queryByPkEnts(enpIds);
    }

    @Override
    public List<ProblemLogVO> queryProblemLogByTimeAndReason(String tenantId, String[] problemName,
                                                             String range, String orgId) throws BusinessException {
        // 查询问题原因pk
        if (ArrayUtils.isEmpty(problemName))
            return null;
        ProblemReasonVO[] problemReasonVOS = reasonQuery.queryIdByNames(problemName, tenantId);
        if (ArrayUtils.isEmpty(problemReasonVOS))
            return null;
        String[] pkReasons = new String[problemReasonVOS.length];
        for (int i = 0; i < problemReasonVOS.length; i++) {
            pkReasons[i] = problemReasonVOS[i].getPkReason();
        }
        // 查询该组织、时间段内、问题原因下的所有的问题记录
        String[] projectIds = queryProjectsOfOrg(tenantId, orgId);
        String startTime = getStartTime(range);
        List<ProblemLogVO> logVOS = null;
        if (pkReasons.length == 1) {
            logVOS = mapper.queryProblemReport(tenantId, startTime, pkReasons[0], projectIds);
        }
        if (pkReasons.length > 1) {
            logVOS = mapper.queryOtherProblemReport(tenantId, startTime, pkReasons, projectIds);
        }

        return logVOS;
    }

    @Override
    public List<ProblemLogVO> queryNotEndProblemLogByRectsAndProjects(String tenantId, String[] pkRectificationers,
                                                                      String[] pkProjects) throws BusinessException {
        if (ArrayUtils.isEmpty(pkRectificationers)) {
            return null;
        }

        return mapper.queryNotEndProblemLogByRectsAndProjects(tenantId, pkRectificationers, pkProjects,
                ProblemLogBillStatus.STATUS_END);
    }

    @Override
    public List<ProblemReportVO> queryProblemReportByEntAndOverdue(String tenantId, String pkEnterprise,
                                                                   String enterpriseName, byte overdue,
                                                                   String orgId) throws BusinessException {
        // 查询项目的团队成员中属于该施工单位的成员
        String[] pkProjects = queryProjectsOfOrg(tenantId, orgId);
        Map<String, TeamMemberVO> memberMap = teamMemberQuery.queryMembersByEntAndProjects(tenantId, pkEnterprise, pkProjects);
        String[] memberIds = teamMapper.queryMembersByEnt(tenantId, pkEnterprise);
        String[] projectIds = teamMapper.queryProjectsByEnt(tenantId, pkEnterprise);

        // 通过整改人和项目查询所有未关闭的问题记录
        List<ProblemLogVO> problemLogVOS = queryNotEndProblemLogByRectsAndProjects(tenantId, memberIds, projectIds);
        if (problemLogVOS == null)
            return null;
        // 根据项目id和成员id筛选问题记录
        List<ProblemLogVO> currLogVOs = new ArrayList<>();
        for (ProblemLogVO vo : problemLogVOS) {
            String userAndPro = vo.getPk_rectificationer() + vo.getPk_project();
            if (memberMap.get(userAndPro) != null) {
                currLogVOs.add(vo);
            }
        }
        // 根据是否超期标识筛选问题记录
        List<ProblemLogVO> logVOsList = getProblemLogByFilter(currLogVOs, overdue);
        if (logVOsList == null)
            return null;
        List<ProblemReportVO> reportVOs = new ArrayList(logVOsList.size());
        // 查询项目名
        Map<String, String> projectMap = queryProjectNames(logVOsList);
        // 查询工序名
        Map<String, String> procedureMap = queryProcedureNames(logVOsList);
        // 查询问题原因名字
        Map<String, String> reasonMap = queryProblemReasonNames(logVOsList);
        // 组装ProblemReport
        fillProblemReports(logVOsList, reportVOs, projectMap, procedureMap, reasonMap, enterpriseName, overdue);

        return reportVOs;
    }

    @Override
    public List<ProblemReportVO> queryProblemReportByRangeAndReason(String tenantId, String[] problemName, String range, Map<String, String> userIdMap, String orgId) throws BusinessException {
        List<ProblemLogVO> results = queryProblemLogByTimeAndReason(tenantId, problemName, range, orgId);
        if (results == null || results.size() == 0)
            return null;
        List<ProblemReportVO> reportVOs = new ArrayList(results.size());
        // 查询web问题名是“其他”的所有问题原因名
        Map<String, String> reasonMap = null;
        if (problemName != null && problemName.length > 1) {
            reasonMap = queryProblemReasonNames(results);
        }
        // 查询到项目名
        Map<String, String> projectMap = queryProjectNames(results);
        // 通过工序id查询所有工序名
        Map<String, String> procedureMap = queryProcedureNames(results);
        // 组装ProblemReport
        fillProblemReports(results, reportVOs, projectMap, procedureMap, userIdMap, reasonMap, problemName);

        return reportVOs;
    }

    @Override
    public List<ProblemReasonViewVO> queryProblemLogAnalyseByReason(String tenantId, String pkSrcOrg, String[] pkProblemReason, String startDate, String endDate) throws BusinessException {
        Map<String, List<ProjectVO>> projectMap = projectSimpleQuery.queryProjectsByOrgs(tenantId, new String[]{pkSrcOrg});

        if (projectMap.get(pkSrcOrg) == null || projectMap.get(pkSrcOrg).isEmpty())
            throw new BusinessException("该用户没有项目权限");

        List<String> projectList = new ArrayList<String>();
        Map<String, ProjectVO>  pkProjectMap = new HashMap<>();
        for (ProjectVO projectVO : projectMap.get(pkSrcOrg)) {
            projectList.add(projectVO.getPkProject());
            pkProjectMap.put(projectVO.getPkProject(), projectVO);
        }
        List<ProblemLogVO> proLogList = new ArrayList<>();
        if (pkProblemReason.length == 1) {
            proLogList = mapper.queryProblemLogAnalyseByReason(tenantId, projectList.toArray(new String[0]), pkProblemReason[0], startDate, endDate);
        }
        if(pkProblemReason.length > 1){
            proLogList = mapper.queryOtherProblemLogAnalyseByReason(tenantId, projectList.toArray(new String[0]), pkProblemReason, startDate, endDate);
        }

        Map<String, List<ProblemLogVO>> problemMap = new HashMap<>();
        List<ProblemReasonViewVO> problemReasonList = new ArrayList<>();
        for(ProblemLogVO logVO : proLogList){
            if(problemMap.get(logVO.getPk_project()) == null){
                problemMap.put(logVO.getPk_project(), new ArrayList<ProblemLogVO>());
            }
            problemMap.get(logVO.getPk_project()).add(logVO);
        }
        for(String pkProject: problemMap.keySet()){
            ProblemReasonViewVO viewVO = new ProblemReasonViewVO();
            viewVO.setProjectCode(pkProjectMap.get(pkProject).getScode());
            viewVO.setProjectName(pkProjectMap.get(pkProject).getSname());
            viewVO.setProblemCount(problemMap.get(pkProject).size());
            viewVO.setManager(pkProjectMap.get(pkProject).getManager());
            problemReasonList.add(viewVO);
        }
        Collections.sort(problemReasonList);
        return problemReasonList;
    }

    /**
     * 根据是否超期标识来筛选问题记录
     *
     * @param problemLogVOS
     * @param isOverdue
     * @return 问题记录VO集合
     * @throws BusinessException
     */
    private List<ProblemLogVO> getProblemLogByFilter(List<ProblemLogVO> problemLogVOS, byte isOverdue) throws BusinessException {
        List<ProblemLogVO> results = new ArrayList<>();
        Date endDate = null;
        if (isOverdue == ProblemReportVO.PROBLEM_ALL) {
            return problemLogVOS;
        } else if (isOverdue == ProblemReportVO.PROBLEM_OVERDUE) {
            for (ProblemLogVO logVO : problemLogVOS) {
                // 整改日期不填则不判断超期
                if (logVO.getEnddate() != null) {
                    endDate = fillTimeInfo(logVO.getEnddate());
                    if (endDate != null && endDate.before(Calendar.getInstance().getTime()))
                        results.add(logVO);
                }
            }
        } else {
            for (ProblemLogVO logVO : problemLogVOS) {
                // 整改日期不填则不判断超期
                if (logVO.getEnddate() != null) {
                    endDate = fillTimeInfo(logVO.getEnddate());
                    if (endDate != null && endDate.after(Calendar.getInstance().getTime()))
                        results.add(logVO);
                } else {
                    results.add(logVO);
                }
            }
        }

        return results;
    }

    /**
     * 查询组织下的项目
     *
     * @param tenantId
     * @param orgId
     * @return
     */
    private String[] queryProjectsOfOrg(String tenantId, String orgId) {
        if (StringUtils.isEmpty(orgId))
            return null;
        ProjectVO[] projectVOS = projectMapper.queryPrjByOrgs(tenantId, new String[]{orgId}, null);
        if (ArrayUtils.isEmpty(projectVOS))
            return null;
        List<String> projectIds = new ArrayList<>(projectVOS.length);
        for (ProjectVO vo : projectVOS) {
            projectIds.add(vo.getPkProject());
        }

        return projectIds.toArray(new String[projectIds.size()]);
    }

    /**
     * 获取查询的起始时间(字符串)
     *
     * @param range
     * @return
     */
    private String getStartTime(String range) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(calendar.getTime());
        if (FILTER_CODE_THREE_MONTH.equalsIgnoreCase(range)) {
            calendar.add(Calendar.MONTH, -3);
        } else if (FILTER_CODE_HALF_YEAR.equalsIgnoreCase(range)) {
            calendar.add(Calendar.MONTH, -6);
        } else if (FILTER_CODE_A_YEAR.equalsIgnoreCase(range)) {
            calendar.add(Calendar.YEAR, -1);
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        return simpleDateFormat.format(calendar.getTime());
    }

    /**
     * 查询问题原因名称
     *
     * @param results
     * @return map, key是问题原因pk，value是名称
     */
    private Map<String, String> queryProblemReasonNames(List<ProblemLogVO> results) throws BusinessException {
        if (results == null || results.size() == 0)
            return null;
        // 通过问题原因id查询所有的原因名称
        Set<String> reasonIdSet = new HashSet<>();
        String currPkReason = null;
        for (ProblemLogVO logVO : results) {
            currPkReason = logVO.getPk_problemreason();
            if (!StringUtils.isEmpty(currPkReason)) {
                reasonIdSet.add(currPkReason);
            }
        }
        if (reasonIdSet.size() == 0)
            return null;
        Map<String, String> reasonMap = reasonQuery.queryNameByIds(reasonIdSet.toArray(new String[reasonIdSet.size()]));

        return reasonMap;
    }

    /**
     * 查询项目名称
     *
     * @param results
     * @return map, key是项目id，value是项目名
     */
    private Map<String, String> queryProjectNames(List<ProblemLogVO> results) throws BusinessException {
        if (results == null || results.size() == 0)
            return null;
        Set<String> projectIdSet = new HashSet<>();
        String currProjectId = null;
        for (ProblemLogVO logVO : results) {
            currProjectId = logVO.getPk_project();
            if (!StringUtils.isEmpty(currProjectId)) {
                projectIdSet.add(logVO.getPk_project());
            }
        }
        if (projectIdSet.size() == 0)
            return null;
        Map<String, String> projectMap = projectSimpleQuery.queryProjectNameByIds(projectIdSet.toArray(new String[projectIdSet.size()]));

        return projectMap;
    }

    /**
     * 查询工序名称
     *
     * @param results
     * @return map，key是工序id，value是工序名称
     */
    private Map<String, String> queryProcedureNames(List<ProblemLogVO> results) throws BusinessException {
        if (results == null || results.size() == 0)
            return null;
        Set<String> procedureIdSet = new HashSet<>();
        String currProcedureId = null;
        for (ProblemLogVO logVO : results) {
            currProcedureId = logVO.getPk_process();
            if (!StringUtils.isEmpty(currProcedureId)) {
                procedureIdSet.add(currProcedureId);
            }
        }
        if (procedureIdSet.size() == 0)
            return null;
        Map<String, String> procedureMap = procedureQuery.queryNameByIds(procedureIdSet.toArray(new String[procedureIdSet.size()]));

        return procedureMap;
    }

    /**
     * 填充报表VO-问题多发分析
     *
     * @param results
     * @param reportVOs
     * @param projectMap
     * @param procedureMap
     * @param userIdMap
     * @param reasonMap
     * @param problemName
     */
    private void fillProblemReports(List<ProblemLogVO> results, List<ProblemReportVO> reportVOs,
                                    Map<String, String> projectMap, Map<String, String> procedureMap,
                                    Map<String, String> userIdMap, Map<String, String> reasonMap, String[] problemName) throws BusinessException {
        if (results == null || results.size() == 0 || ArrayUtils.isEmpty(problemName))
            return;
        String pkProject = null;
        String pkProcedure = null;
        String userAndProject = null;
        for (ProblemLogVO logVO : results) {
            ProblemReportVO reportVO = new ProblemReportVO();
            pkProject = logVO.getPk_project();
            pkProcedure = logVO.getPk_process();
            userAndProject = logVO.getPk_rectificationer() + logVO.getPk_project();
            if (projectMap != null && !StringUtils.isEmpty(pkProject))
                reportVO.setProjectName(projectMap.get(pkProject));
            if (procedureMap != null && !StringUtils.isEmpty(pkProcedure))
                reportVO.setProcedureName(procedureMap.get(pkProcedure));
            if (userIdMap != null && !StringUtils.isEmpty(userAndProject))
                reportVO.setEnterpriseName(userIdMap.get(userAndProject));
            if (problemName.length == 1)
                reportVO.setProblemReasonName(problemName[0]);
            if (problemName.length > 1 && reasonMap != null) {
                String pkReason = logVO.getPk_problemreason();
                reportVO.setProblemReasonName(reasonMap.get(pkReason));
            }
            reportVO.setEndDate(logVO.getEnddate());
            reportVO.setProblemStatus(logVO.getBillstatus());
            reportVO.setPkRectificationer(logVO.getPk_rectificationer());
            // 设置是否超期
            reportVO.setOverdue(getOverdue(logVO.getEnddate()));
            reportVOs.add(reportVO);
        }
    }

    /**
     * 获取超期标识
     * @param date 结束日期
     * @return 0：未超期，1：已超期，2：显示全部（未超期+已超期）
     */
    private byte getOverdue(Date date) throws BusinessException {
        if (date != null) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String endDateStr = simpleDateFormat.format(date) + " 23:59:59";
            Date endDate;
            try {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                endDate = dateFormat.parse(endDateStr);
            } catch (ParseException e) {
                e.printStackTrace();
                log.error(e.getMessage(), e);
                throw new BusinessException("parse date :" + e.getMessage());
            }
            if (endDate != null && endDate.before(Calendar.getInstance().getTime())) {
                return ProblemReportVO.PROBLEM_OVERDUE;
            } else {
                return ProblemReportVO.PROBLEM_NOT_OVERDUE;
            }
        } else {
            return ProblemReportVO.PROBLEM_NOT_OVERDUE;
        }
    }

    /**
     * 给日期填充时间信息
     *
     * @param endDate
     * @return 带具体时间的Date
     */
    private Date fillTimeInfo(Date endDate) throws BusinessException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String endDateStr = simpleDateFormat.format(endDate) + " 23:59:59";
        try {
            endDate = dateFormat.parse(endDateStr);
        } catch (ParseException e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
            throw new BusinessException("parse date :" + e.getMessage());
        }

        return endDate;
    }

    /**
     * 填充报表VO-未关闭问题统计
     *
     * @param logVOsList
     * @param reportVOs
     * @param projectMap
     * @param procedureMap
     * @param reasonMap
     * @param enterpriseName
     */
    private void fillProblemReports(List<ProblemLogVO> logVOsList, List<ProblemReportVO> reportVOs,
                                    Map<String, String> projectMap, Map<String, String> procedureMap,
                                    Map<String, String> reasonMap, String enterpriseName, byte overdue) throws BusinessException {
        String pkProject = null;
        String pkProcedure = null;
        String pkReason = null;
        for (ProblemLogVO logVO : logVOsList) {
            ProblemReportVO reportVO = new ProblemReportVO();
            pkProject = logVO.getPk_project();
            pkProcedure = logVO.getPk_process();
            pkReason = logVO.getPk_problemreason();
            if (projectMap != null && !StringUtils.isEmpty(pkProject)) {
                reportVO.setProjectName(projectMap.get(pkProject));
            }
            if (procedureMap != null && !StringUtils.isEmpty(pkProcedure)) {
                reportVO.setProcedureName(procedureMap.get(pkProcedure));
            }
            if (reasonMap != null && !StringUtils.isEmpty(pkReason)) {
                reportVO.setProblemReasonName(reasonMap.get(pkReason));
            }
            reportVO.setEnterpriseName(enterpriseName);
            reportVO.setEndDate(logVO.getEnddate());
            reportVO.setProblemStatus(logVO.getBillstatus());
            reportVO.setPkRectificationer(logVO.getPk_rectificationer());
            if (overdue == ProblemReportVO.PROBLEM_ALL) {
                // 整改日期不填则不判断超期
                if (logVO.getEnddate() != null) {
                    reportVO.setOverdue(getOverdue(logVO.getEnddate()));
                } else {
                    reportVO.setOverdue(ProblemReportVO.PROBLEM_NOT_OVERDUE);
                }
            } else {
                reportVO.setOverdue(overdue);
            }
            reportVOs.add(reportVO);
        }
    }


}
